package com.lhl.jwt.resolver;

import com.lhl.fw.core.userinfo.UserInfo;
import com.lhl.jwt.annotation.CurrentUser;
import com.lhl.jwt.domain.dto.PayloadDTO;
import com.lhl.jwt.utils.JwtConstant;
import com.lhl.jwt.utils.JwtUtils;
import com.nimbusds.jwt.SignedJWT;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @className: com.lhl.jwt.resolver.LoginUserHandlerMethodArgumentResolver
 * @description: 在方法参数中把token的信息转换成用户信息
 * @author: king
 * @date: 2021-01-05 9:04
 **/
@Api(tags = "LoginUserHandlerMethodArgumentResolver", produces = "LoginUserHandlerMethodArgumentResolver")
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(CurrentUser.class) &&
                parameter.getParameterType().isAssignableFrom(UserInfo.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest request, WebDataBinderFactory webDataBinderFactory) throws Exception {
        // header中获取用户token
        String token = getJwtToken(request);
        SignedJWT signedJWT = SignedJWT.parse(token);
        String username = signedJWT.getJWTClaimsSet().getSubject();
        PayloadDTO payloadDTO = JwtUtils.getPayLoadByToken(token,username);
        // TODO 根据userId获取User信息，这里省略，直接创建一个User对象。
        UserInfo user = new UserInfo();
        user.setName(payloadDTO.getUsername());
        return user;
    }
    private String getJwtToken(NativeWebRequest request) {
        String authInfo = request.getHeader(JwtConstant.AUTHORIZATION_HEADER);
        if (StringUtils.isBlank(authInfo)) {
            throw new BadCredentialsException(JwtConstant.TOKEN_NOT_EMPTY);
        }
        return StringUtils.removeStart(authInfo, JwtConstant.AUTHORIZATION_START_STRING);
    }
}
